package com.lyd.management.common;

import com.lyd.management.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Base64Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Enumeration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class Utils {

    @Autowired
    private RedisCache redisCache;
    public static RedisCache staticRedisCache;

    @PostConstruct
    public void init() {
        Utils.staticRedisCache = redisCache;
    }

    public static String getCurrentUserIdByRequest(HttpServletRequest request) {
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (token != null) {
            // 如果本次请求携带了token，就重置该token的计时
            staticRedisCache.expire(token, 5, TimeUnit.MINUTES);
            //TimeUnit.MINUTES 时间单位：分钟
            return staticRedisCache.getCacheObject(token);
        }
        return null;
    }

    public static String setCurrentUserIdToRedis(String id) {
        // 生成随机UUID    --- abcdefg
        String uuid = UUID.randomUUID().toString();
        // 将uuid:userId存入redis，并设置超时为5分钟
        // --- key: abcdefg
        // --- value: id
        staticRedisCache.setCacheObject(uuid, id, 5, TimeUnit.MINUTES);
        //键：uuid
        //值：id
        //redis保存数据都是键值对的形式
        // 返回随机生成的uuid
        return uuid;
    }



    public static String encodeImageToBase64(String path) throws IOException {

        //读取图片变成字节数组
        ByteArrayOutputStream bos;
        int len = -1;
        try (FileInputStream fileInputStream = new FileInputStream(path)) {

            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            while ((len = fileInputStream.read(b)) != -1) {
                bos.write(b, 0, len);
            }
        }
        byte[] fileByte = bos.toByteArray();


        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(fileByte);
    }










}
